package com.sxt.practiceapplication.activities.course;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.Image;
import android.os.Environment;

import com.sxt.practiceapplication.utils.LogUtil;
import com.sxt.practiceapplication.utils.PermissionManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class ImageSaver implements Runnable {

    private final Image mImage;

    private Context context;

    public ImageSaver(Image image, Context context) {
        mImage = image;
        this.context = context;
    }

    @Override
    public void run() {
        File mImageFile = new File(context.getFilesDir() + "/myPicture.jpg");
        if(!mImageFile.exists()) {
            try {
                mImageFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (FileOutputStream fos = new FileOutputStream(mImageFile)) {
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] data = new byte[buffer.remaining()];
            buffer.get(data);
            fos.write(data, 0, data.length);
            Bitmap oldMap = BitmapFactory.decodeFile(mImageFile.getAbsolutePath());
            Matrix matrix = new Matrix();
            matrix.setScale(-1.0f, 1.0f);
            oldMap = Bitmap.createBitmap(oldMap, 0, 0, oldMap.getWidth(), oldMap.getHeight(), matrix, true);
            try {
                FileOutputStream out = new FileOutputStream(mImageFile);
                oldMap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            mImage.close();
        }
    }
}